package com.we823.project.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.we823.project.core.web.WebConstants;
import com.we823.project.extra.handler.ExceptionResponse;
import com.we823.project.model.RoleModel;
import com.we823.project.model.UserModel;
import com.we823.project.model.we.ResourceModel;
import com.we823.project.model.we.RoleResourcePermissionModel;
import com.we823.project.repository.service.sys.RoleService;
import com.we823.project.repository.service.we.ResourceService;
import com.we823.project.repository.service.we.RoleResourcePermissionService;
import com.we823.utils.web.RequestUtil;
import com.we823.utils.web.StringUtil;

@Controller
public class IndexController {

	private Logger logger = LoggerFactory.getLogger(IndexController.class);
	
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private RoleResourcePermissionService roleResourcePermissionService;
	@Autowired
	private RoleService roleService;
	
	@RequestMapping("index")
	public String index(HttpServletRequest request,Model model){
		List<ResourceModel> resources = resourceService.getListInMapByParentid(0);

		HttpSession session = request.getSession();
		UserModel userModel = (UserModel) session.getAttribute(WebConstants.CURRENT_USER);
		String roleIds = null;
		if(userModel!=null) {
			roleIds = userModel.getRoleIds();
			if (StringUtils.isEmpty(roleIds)) {
				Throwable throwable = new Exception("用户："+userModel.getUsername()+" 设置的角色为空，请分配角色！");
				
				ExceptionResponse exceptionResponse = ExceptionResponse.from(throwable);
				model.addAttribute("error",exceptionResponse);
				
				return "/error/exception";
			}
			List<Integer> roleIdList = new ArrayList<>();
			StringUtil.toIntegerList(roleIds, roleIdList);
			List<RoleModel> roleModels = roleService.findByIdIn(roleIdList);
			if(roleModels!=null && roleModels.size()>0) {
				RoleModel roleModel = roleModels.get(0);
				String indexUrlString = roleModel.getIndex();
				String contextPath = request.getContextPath();
				
				indexUrlString = contextPath+indexUrlString;
				indexUrlString = StringUtils.replace(indexUrlString, "//", "/");
				
				model.addAttribute("indexUrl",indexUrlString);
			}
		}
		model.addAttribute("user",userModel);
		
		if(roleIds!=null) {
			List<Integer> roleIdList = new ArrayList<>();
			if(!StringUtils.isBlank(roleIds)) {
				StringUtil.toIntegerList(roleIds, roleIdList);
			}
			if(roleIdList!=null && roleIdList.size()>0) {
				List<RoleResourcePermissionModel> roleResourcePermissionModels = roleResourcePermissionService.findByRoleidIn(roleIdList);
				List<Integer> resourceIdList = new ArrayList<>();
				if (roleResourcePermissionModels!=null && roleResourcePermissionModels.size()>0) {
					for (RoleResourcePermissionModel roleResourcePermissionModel : roleResourcePermissionModels) {
						resourceIdList.add(roleResourcePermissionModel.getResourceid());
					}
				}
				
				if(resourceIdList.size()>0) {
					List<ResourceModel> customResources = new ArrayList<>();
					buildCutomResource(customResources,resources,resourceIdList);
					model.addAttribute("resources",customResources);
				}
				
			}
		}

		return "index";
	}

	private void buildCutomResource(List<ResourceModel> customResources,List<ResourceModel> resources, List<Integer> resourceIdList) {
		if (resourceIdList!=null && resourceIdList.size()>0) {		
			if(resources!=null && resources.size()>0) {
				if(customResources==null) {
					customResources = new ArrayList<>();
				}
				for (ResourceModel resourceModel : resources) {
					if (resourceIdList.contains(resourceModel.getId())) {
						if(resourceModel!=null) {
							ResourceModel copyResourceModel = resourceModel;
							List<ResourceModel> subresources = new ArrayList<>();
							buildCutomResource(subresources, resourceModel.getSubresources(), resourceIdList);
							copyResourceModel.setSubresources(subresources);
							customResources.add(copyResourceModel);
						}
					}
				}
			}
		}
		
	}



	@RequestMapping(value="login",method=RequestMethod.GET)
	public String login(HttpServletRequest request,Model model){
		logger.debug("login get");
		
		int notfound=RequestUtil.getValueByParam(request, "nofound", 0);
		int logout = RequestUtil.getValueByParam(request, "logout", 0);
		int blocked = RequestUtil.getValueByParam(request, "blocked", 0);
		int unknown = RequestUtil.getValueByParam(request, "unknown", 0);
		
		boolean hasError = false;
		String message = "";
		if(notfound==1) {
			hasError=true;
			message = "用户名密码错误！";
		}
		if(logout==1) {
			hasError=true;
			message="你已成功退出系统";
		}
		if(blocked==1) {
			hasError=true;
			message="帐号被锁定了，无法进入系统";
		}
		if(unknown==1) {
			hasError=true;
			message="发生未知错误，无法进入系统";
		}
		AuthenticationException ae = (AuthenticationException) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		if(ae!=null) {
			hasError = true;
			message = "用户名或密码错误，无法进入系统";
		}
		model.addAttribute("hasError",hasError);
		model.addAttribute("message",message);
		
		//如果用户直接到登录页面 先退出一下
        //原因：isAccessAllowed实现是subject.isAuthenticated()---->即如果用户验证通过 就允许访问
        // 这样会导致登录一直死循环
        
		Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
        	if(subject.isAuthenticated()) {
        		subject.logout();
        	}
        }
        
        Cookie[] cookies = request.getCookies();
        boolean isRememberMe = false;
        String rememberUser = "";
        if(cookies!=null) {
        	for (Cookie cookie : cookies) {
				String name = cookie.getName();
				if("materialRememberMe".equals(name)) {
					String rememberMe = cookie.getValue();
					if("true".equals(rememberMe.trim().toLowerCase())) {
						isRememberMe = true;
					}
				}
				
				if("materialUserCookie".equals(name)) {
					rememberUser = cookie.getValue();
				}
			}
        }
        if (isRememberMe) {
			model.addAttribute("username",rememberUser);
		}
		return "login";
	}
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(HttpServletRequest request,HttpServletResponse response,Model model){
		logger.debug("login post");
		
		int notfound=RequestUtil.getValueByParam(request, "nofound", 0);
		int logout = RequestUtil.getValueByParam(request, "logout", 0);
		int blocked = RequestUtil.getValueByParam(request, "blocked", 0);
		int unknown = RequestUtil.getValueByParam(request, "unknown", 0);
		
		boolean hasError = false;
		String message = "";
		if(notfound==1) {
			hasError=true;
			message = "用户名密码错误！";
		}
		if(logout==1) {
			hasError=true;
			message="你已成功退出系统";
		}
		if(blocked==1) {
			hasError=true;
			message="帐号被锁定了，无法进入系统";
		}
		if(unknown==1) {
			hasError=true;
			message="发生未知错误，无法进入系统";
		}
		AuthenticationException ae = (AuthenticationException) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		if(ae!=null) {
			hasError = true;
			message = "用户名或密码错误，无法进入系统";
		}
		model.addAttribute("hasError",hasError);
		model.addAttribute("message",message);
		
		return "login";
	}
	
	@RequestMapping("manage")
	public String manage(HttpServletRequest request){
		return "manage";
	}
	
	@RequestMapping("unauthorized")
	public String unauthorized(HttpServletRequest request,Model model) {
		return "unauthorized";
	}

	public ResourceService getResourceService() {
		return resourceService;
	}

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	public RoleResourcePermissionService getRoleResourcePermissionService() {
		return roleResourcePermissionService;
	}

	public void setRoleResourcePermissionService(
			RoleResourcePermissionService roleResourcePermissionService) {
		this.roleResourcePermissionService = roleResourcePermissionService;
	}

	public RoleService getRoleService() {
		return roleService;
	}
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
}
